package com.freewater.library.lending.reader.eventhandler;

import com.freewater.library.lending.book.model.event.*;
import com.freewater.library.lending.reader.application.ReaderCommandService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
@RequiredArgsConstructor
public class ReaderEventConsumer {

    private final ReaderCommandService readerCommandService;

    @Transactional
    @EventListener(BookInstanceReservedEvent.class)
    public void onBookInstanceReservedEvent(BookInstanceReservedEvent event) {
        Long readerId = event.getReaderId();
        String qrCode = event.getQrCode();
        readerCommandService.reservedBook(readerId, qrCode);
    }

    @Transactional
    @EventListener(BookInstanceReserveCanceledEvent.class)
    public void onBookInstanceReservedEvent(BookInstanceReserveCanceledEvent event) {
        Long readerId = event.getReaderId();
        String qrCode = event.getQrCode();
        readerCommandService.canceledReservedBook(readerId, qrCode);
    }

    @Transactional
    @EventListener(BookInstanceCheckedOutEvent.class)
    public void onBookInstanceReservedEvent(BookInstanceCheckedOutEvent event) {
        Long readerId = event.getReaderId();
        String qrCode = event.getQrCode();
        readerCommandService.checkedOutBook(readerId, qrCode);
    }

    @Transactional
    @EventListener(BookInstanceCheckedOutOverdueEvent.class)
    public void onBookInstanceReservedEvent(BookInstanceCheckedOutOverdueEvent event) {
        Long readerId = event.getReaderId();
        String qrCode = event.getQrCode();
        readerCommandService.checkedOutOverdue(readerId, qrCode);
    }

    @Transactional
    @EventListener(BookInstanceReturnedEvent.class)
    public void onBookInstanceReservedEvent(BookInstanceReturnedEvent event) {
        Long readerId = event.getReaderId();
        String qrCode = event.getQrCode();
        readerCommandService.returnedBackBook(readerId, qrCode);
    }

    @Transactional
    @EventListener(BookInstanceLostEvent.class)
    public void onBookInstanceReservedEvent(BookInstanceLostEvent event) {
        Long readerId = event.getReaderId();
        String qrCode = event.getQrCode();
        readerCommandService.checkedOutBookLost(readerId, qrCode);
    }
}
